<!--websocket组件-->
<template>
  <span class="mc-websocket"><slot></slot></span>
</template>

<script>
  import McCommon from "./McCommon"
export default {
  name: 'mc-websocket',
  data () {
    return {
      ws:null,
      wsInterval:null,
      wsReConnectTimes:0
    }
  },
  //暂时预定10个参数 大部分用户2-3个就够了
  props: {
    //业务场景
    mcKey:{type:String,default:null},
    //断线重连
    reconnect:{type:Boolean,default:true},
    //向谁发送消息
    sendTo:{type:String,default:".*"},
    //着是函数 当前用户信息
    getUserKey:{type:Function,default:null},
  }
  ,
  mounted(){
      this.websocket();
  },
  methods:{
    send:function ({key,sendTo,message}) {
      sendTo=sendTo||this.sendTo;
      key=key||this.mcKey;
      this.ws.send(JSON.stringify({key:key,sendTo:sendTo,message:message}))
    },
    websocket:async function () {
      if("WebSocket" in window){
        var _t = this;
        if(this.wsReConnectTimes<30){
          this.wsReConnectTimes++;
        }else {
          console.log("超过重连次数，不再尝试连接")
          return;
        }
        //获取当前登录的管理后台用户
        if(!this.mcKey){
          this.$message({type:"warning",message:"请配置使用场景KEY"});
          return ;
        }
        var userKey = "";
        if(this.getUserKey){
          userKey = await this.getUserKey();
        }else {
          var user = localStorage.getItem("mc-admin-user");
          if(user){
            user = JSON.parse(user);
            userKey = user.username+"-"+McCommon.util.pubGenerateClearUUID();
          }else {
            var res = await $magicaltool.request.axios({cache:true,$vue:this,url:"/magical_lowcode/manager/user/info",method:"get",param:{},reject:false});
            if(res.code==0&&res.data){
              userKey = res.data.username+"-"+McCommon.util.pubGenerateClearUUID();
            }
          }
        }
        if(!userKey) {//随机生成一个字符串赋予它
          userKey = McCommon.util.pubGenerateClearUUID();
        }
        //构建url ws/openapi/{key}/{userKey} 其中key可以指定使用场景 userKey是该场景下的标识用户信息的字符串 请自由发挥
        var url = $magicaltool.request.util.wrapCtxPath("ws/openapi/"+this.mcKey+"/"+userKey);
        var loc = window.location;
        if(loc.protocol.indexOf('https')!=-1){
          url = "wss://"+loc.host+url;
        }else {
          url = "ws://"+loc.host+url;
        }
        console.log(url);
        var ws = new WebSocket(url); //创建WebSocket连接
        this.ws = ws;
        ws.onopen = function(){
          _t.$emit("onopen",null);
          //当WebSocket创建成功时，触发onopen事件
          console.log("open websocket success!!!");
          // ws.send("hello"); //将消息发送到服务端
        }
        ws.onmessage = function(e){
          _t.$emit("onmessage",{message:e.data});
          //当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
//          console.log("收到消息",e.data)
        }
        ws.onclose = function(e){
          console.log('断线')
          console.log(e)
          _t.$emit("onclose",e);
          //当客户端收到服务端发送的关闭连接请求时，触发onclose事件
          if(this.reconnect){
            setTimeout(function () {
              console.log('重连..')
              _t.websocket();//重连
            },15000)
          }
        }
        ws.onerror = function(e){
          console.log('error')
          _t.$emit("onerror",e.data);
          //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
          console.log(e);
        }

        if(this.wsInterval){
          window.clearInterval(this.wsInterval)
        }
        this.wsInterval = setInterval(function () {
          _t.ws.send('');//保持不断开
        }, 1000 * 30)
      }else{
        console.log("您的浏览器不支持WebSocket");
      }
    }
  },
  destroyed(){

  }
}
</script>

<style lang="scss">
    .mc-websocket{
        display:none;
    }
    .magicalcoder-dragging .mc-websocket{
        display:inline-block;
        font-size: 20px;
        color: red;
    }
</style>
